package com.an.web;

import com.an.domain.LoginCommand;
import com.an.domain.User;
import com.an.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/index.html")
    public String LoginPage(){
        return  "login";
    }

    @RequestMapping("/login.html")
public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand){

        boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(),loginCommand.getPassword());

        if(!isValidUser){
            System.out.println("登录失败，当前用户：" + loginCommand);

            return  new ModelAndView("login","error","用户名或者密码错误");
        }else{
            User user = userService.findUserByUserName(loginCommand.getUserName());
            user.setLastIp(request.getLocalAddr());
            user.setLastVisit(new Date());
            System.out.println("当前用户：" + user);
            userService.loginSuccess(user);
            request.getSession().setAttribute("user",user);
            return  new ModelAndView("main");
        }

    }
}
